<template>
    <div>
        <!-- 歌单详情 -->
        <!-- 动态绑定显示背景图片 -->
        <el-container>
            <div class="backgroundimg">
                    <el-image :src="coverimgurl"  style="width:100%" ></el-image>
                </div>
        <el-header class="header">
            <div class="info">
                <el-row>
                    <el-col :span="8" >
                        <div class="coverimg">
                            <el-image  :src="coverimgurl" >
                            </el-image>
                        </div>

                    </el-col>
                    <el-col :span="16">
                        <div class="name">{{songsheetname}}</div>
                        <div class="creator">
                            <el-image @click="linkToSubscribers(playlist.creator.userId)" class="avatarimg" :src="coveravatarUrl"></el-image>
                            <div class="nickname">{{covernickname}}</div>
                        </div>
                    <!-- 清除浮动 -->
                        <div class="clearfix"></div>
                        <div class="subscribers">
                            <span class="subscribers-txt">订阅者：</span>
                            <div class="subscribers-avatar" v-for="item in playlist.subscribers" :key="item.userId">
                                <el-image @click="linkToSubscribers(item.userId)" class="avatarimg" :src="item.avatarUrl" ></el-image>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <div class="playnumber">
                            <span class="playcount-txt">播放量：</span>
                            <div class="playcount">{{playlist.playCount | countFormat}}</div>
                        </div>

                        <div class="tags" v-for="item in playlist.tags" :key="item">
                            <span class="songsheet-tag">#{{item}}</span>
                        </div>
                        <div class="clearfix"></div>
                        <div class="description" >简介：{{playlist.description}}</div>

                    </el-col>
                </el-row>
             </div>
        </el-header>
        <el-main class="main">
            <!-- 歌曲列表 -->
            <el-table
                class="musicTable"
                :data="musiclist"
                style="width: 100%"
                stripe
                fit>
                <el-table-column
                    type="index" label="序号" >
                </el-table-column>
                <el-table-column
                    prop="title"
                    label="歌曲名称"
                    min-width="35%">
                    <template v-slot='scope'>
                        <i v-if="play&&activeIndex===scope.$index" class="el-icon-video-pause" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='stop')"> {{scope.row.title}}</i>
                        <i v-else class="el-icon-video-play" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='broadcast')"> {{scope.row.title}}</i>
                        <el-tag type="danger" size="mini" class="viptag" v-if="!scope.row.src">会员</el-tag>
                    </template>
                </el-table-column>

                <el-table-column
                    label="时长"
                    min-width="20%">
                    <template v-slot="scope">
                    {{scope.row.dt | dtFormat}}
                </template>
                </el-table-column>
                <el-table-column
                    prop="artist"
                    label="歌手"
                    min-width="20%">
                </el-table-column>

            </el-table>
            <!-- 推荐歌单 -->
            <div class="recommend">
                <div class="recommend-txt">推荐歌单</div>
                <div class="recommend-songlist" v-for="item in recommendsonglist" :key="item.id">
                    <div class="recommend-image"  @click="linkToSongsheet(item.id)">
                        <el-image  class="recommend-songlistimg" :src="item.coverImgUrl" ></el-image>
                    </div>

                    <p class="songlist-name">{{item.name}}</p>
                    <div class="recommend-creator">by <span class="creator-name">{{item.creator.nickname}}</span></div>
                </div>
            </div>
            <!-- 用户评论 -->
            <div class="comments">
                <!-- 热门评论 -->
                <div class="comments-txt" >用户评论</div>
                <div class="hot-comments">
                    <div class="comments-title" >热门评论({{hotcommentscount}})</div>
                    <div class="comments-body" v-for="item in hotcommentslist" :key="item.commentId">
                        <el-image @click="linkToSubscribers(item.user.userId)"  class="comments-avatarimg" :src="item.user.avatarUrl" ></el-image>
                        <div class="comments-nickname">{{item.user.nickname}}</div>
                        <div class="comments-time">{{item.time | dateFormat('YYYY-MM-DD hh:mm:ss')}}</div>
                        <!-- 清除浮动 -->
                        <div class="clearfix"></div>
                        <div class="comment-content">{{item.content}}</div>
                        <div class="line"></div>
                    </div>
                </div>
                <!-- 全部评论 -->
                <div class="all-comments">
                    <div class="comments-title">全部评论({{allcommentscount}})</div>
                    <div class="comments-body" v-for="item in allcommentslist" :key="item.commentId">
                        <el-image @click="linkToSubscribers(item.user.userId)"  class="comments-avatarimg" :src="item.user.avatarUrl" ></el-image>
                        <div class="comments-nickname">{{item.user.nickname}}</div>
                        <div class="comments-time">{{item.time | dateFormat('YYYY-MM-DD hh:mm:ss')}}</div>
                        <!-- 清除浮动 -->
                        <div class="clearfix"></div>
                        <div class="comment-content">{{item.content}}</div>
                        <div class="line"></div>
                    </div>
                </div>
                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination
                    v-if="showPaginationVisable"
                    @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :page-size="20"
                    :total="allcommentscount">
                </el-pagination>
                </div>
            </div>
            </el-main>
            <!-- 底部留白 -->
        <el-footer class="footer"></el-footer>

    </el-container>
    <!-- 播放器 -->
    <musicplayer @watch="watchplayer" :aplayerVisible="isShow" :musiclist='musiclist' :music="music" ref="musicplayer"></musicplayer>

    </div>
</template>

<script>
import MusicPlayer from '@/views/musicplayer'
export default {
  inject: ['reload'],
  components: {
    musicplayer: MusicPlayer
  },
  data () {
    return {
      // 歌单信息
      playlist: {},
      //   封面url
      coverimgurl: '',
      //   歌单名称
      songsheetname: '',
      coveravatarUrl: '',
      covernickname: '',
      //   控制播放按钮图标
      activeIndex: 0,
      //   按钮播放状态
      play: false,
      //   控制播放器显示
      isShow: false,
      // 歌曲列表
      music: {},
      musiclist: [],
      //   相关推荐歌单
      recommendsonglist: [],
      //   热门歌单评论
      hotcommentslist: [],
      hotcommentscount: '',
      //   请求获取全部评论 入参
      allcommentqueryinfo: {
        id: '',
        type: 2,
        sortType: 3,
        pageSize: 20,
        pageNo: 1,
        // 当sortType=3，pageNo>1时，需要传cursor，上一个数据中的值
        cursor: ''
      },
      // 全部歌单评论
      allcommentslist: [],
      //   评论总条数
      allcommentscount: '',
      //   控制分页组件的显示，让其在页面加载完后再显示
      showPaginationVisable: false
    }
  },
  created () {
    //   歌单详情
    this.getSongsheetDetail()
    // 推荐歌单
    this.getRecommedSonglist()
    // 热门评论
    this.getHotSongComments()
    // 全部评论
    this.getAllSongComments()
  },
  methods: {
    //   通过 歌单id 获取歌单详情
    getSongsheetDetail () {
      var songsheetid = this.$route.params.id
      this.$http.get('playlist/detail', { params: { id: songsheetid } }).then(({ data: res }) => {
        if (res.code !== 200) return this.$message.error(res.message)
        // 歌单详情
        this.playlist = res.playlist
        // 歌单封面
        this.coverimgurl = this.playlist.coverImgUrl
        // 歌单名称
        this.songsheetname = this.playlist.name
        // 创建者头像昵称
        this.coveravatarUrl = this.playlist.creator.avatarUrl
        this.covernickname = this.playlist.creator.nickname
        // 将歌单详情中 歌曲信息提取存入musiclist
        this.playlist.tracks.forEach(async element => {
        //   console.log(element)
        //   获取歌词
          const songLrc = await this.getSongLrc(element.id)

          this.musiclist.push({
            title: element.name,
            artist: element.ar[0].name,
            src: 'https://music.163.com/song/media/outer/url?id=' + element.id + '.mp3',
            pic: element.al.picUrl,
            dt: element.dt,
            lrc: songLrc
          })
        })

        // console.log('getSongsheetDetail this.musiclist:', this.musiclist)
      }).catch(e => {
        //   捕获异常
        console.log('getSongsheetDetail e:', e.response.data.message)
        if (e.response.data.message === 'no resource') return this.$message.error('歌单不存在')
        this.$message.error(e.response.data.message)
      })
    },
    // 跳转到订阅者的主页
    linkToSubscribers (Id) {
      window.open('https://music.163.com/#/user/home?id=' + Id)
    },
    // 通过nextTick方法，使播放器组件渲染完成后再执行play方法，防止报错,该play方法从vue-aplayer.vue方法中获得
    thenPlay () {
      this.$nextTick(() => {
        console.log(this.$refs.musicplayer.$refs.aplayer)
        this.$refs.musicplayer.$refs.aplayer.play()
      })
    },
    // 通过 id 获取歌词
    async getSongLrc (songId) {
      const { data: res } = await this.$http.get('lyric', { params: { id: songId } })
      if (res.code !== 200) return this.$message.error('获取音乐歌词失败')
      try {
        var songLrc = res.lrc.lyric
        // console.log('songLrc:', songId, songLrc)
        // 如果歌词格式不对，不显示歌词
        if (songLrc.indexOf('[0') === -1) return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      } catch {
        // console.log('songLrc:', songId, songLrc)
        // 没有歌词时,显示 暂无歌词
        return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      }
      return songLrc
    },
    // 播放音乐
    broadcastMusic (index, scopeRow, btnSt) {
    //   console.log(scopeRow)
      // 显示播放器组件
      this.isShow = true
      // 控制播放/暂停icon的显示
      if (btnSt === 'broadcast') {
        this.activeIndex = index
        this.play = true
      } else {
        this.play = false
      }
      //   try catch 判断是否有currentMusic属性，并捕获异常
      try {
        //   判断是否有currentMusic属性，如果有执行暂停或播放选中的另外一首
        if (this.$refs.musicplayer.$refs.aplayer.currentMusic === scopeRow) {
          this.$refs.musicplayer.$refs.aplayer.toggle()
        } else {
          // 将当前currentMusic属性赋予新的song对象
          this.$refs.musicplayer.$refs.aplayer.currentMusic = scopeRow
          this.thenPlay()
        }
      } catch {
        //   如果没有currentMusic属性，执行播放方法
        this.music = scopeRow
        this.thenPlay()
      }
    },
    // 监听播放器 暂停和播放 事件，获得参数 activeIndex和play，控制歌曲列表中播放按钮的播放与暂停
    watchplayer (index, play) {
      console.log('watch', index, play)
      this.activeIndex = index
      this.play = play
    },
    // 获取相关推荐歌单
    getRecommedSonglist () {
      var songsheetid = this.$route.params.id
      this.$http.get('related/playlist', { params: { id: songsheetid } }).then(({ data: res }) => {
        if (res.code !== 200) return this.$message.error(res.message)
        this.recommendsonglist = res.playlists
        console.log('this.recommendsonglist', this.recommendsonglist)
      })
    },
    // 跳转到对应歌单详情
    linkToSongsheet (Id) {
      //   跳转页面
      this.$router.push({ path: `/songsheet/songsheetdetail/${Id}` })
      //   局部刷新页面
      this.reload()
      //   回到顶部
      document.body.scrollTop = 0
      document.documentElement.scrollTop = 0
    },
    // 通过 id 获取 热门歌单评论
    async getHotSongComments () {
      var songsheetid = this.$route.params.id
      const { data: res } = await this.$http.get('comment/hot', { params: { id: songsheetid, type: 2 } })
      if (res.code !== 200) return this.$message.error('获取热门歌单评论失败')
      this.hotcommentslist = res.hotComments
      this.hotcommentscount = res.total
      console.log('hotcommentslist', this.hotcommentslist)
    },
    // 通过 id 获取 全部歌单评论
    async getAllSongComments () {
      var songsheetid = this.$route.params.id
      this.allcommentqueryinfo.id = songsheetid
      console.log('getAllSongComments allcommentqueryinfo', this.allcommentqueryinfo)
      const { data: res } = await this.$http.get('comment/new', { params: this.allcommentqueryinfo })
      if (res.code !== 200) return this.$message.error('获取全部歌单评论失败')
      this.allcommentslist = res.data.comments
      this.allcommentscount = res.data.totalCount
      console.log('getAllSongComments allcommentslist', this.allcommentslist)
      // 如果sortType=3，则将此次请求到的cursor赋给allcommentqueryinfo，为下次请求使用
      if (this.allcommentqueryinfo.sortType === 3) {
        this.allcommentqueryinfo.cursor = res.data.cursor
      }
      // 当列表数据渲染完成后再显示分页控件
      this.$nextTick(() => {
        this.showPaginationVisable = true
      })
    },
    // 监听 页码 变化事件
    handleCurrentChange (pageNum) {
      console.log(pageNum)
      this.allcommentqueryinfo.pageNo = pageNum
      this.getAllSongComments()
    }
  }
}
</script>

<style  scoped>
/* 背景图片 */
.backgroundimg{
    /* 高斯模糊 */
    filter: blur(20px);
    /* 透明度 */
    opacity: 0.3;
    /* 隐藏溢出 */
    width: 100%;
    height: 450px;
    overflow: hidden;
    position: absolute;
    left: 0;
    top: 0;
 }
.header{
    height: 450px !important;
}
/* 歌单信息 */
.info{
    /* z-index: 999; */
    height: 400px;
    padding:3.71429% 0 ;
    margin: 0 auto;
    max-width: 1280px;
    min-width: 920px;

}
/* 封面图片 */
.coverimg{
    width:80%;
    /* 父元素有宽度、父、子组件是块元素时，margin才会生效 */
    display: block;
    margin: 0 auto;
    border-radius: 3px;
}
/* 歌曲创建人头像图片样式 */
.avatarimg{
    width: 25px;
    border-radius: 50%;
    float: left;
    cursor: pointer;
}
/* creator nickname */
.nickname{
    float: left;
    margin-left: 10px;
}
.subscribers-txt{
    float: left;
}
/* 头像 */
.subscribers-avatar{
    float: left;
    margin-left: 5px;
}
/* tags */
.songsheet-tag{
    float: left;
    margin-left: 2px;
    margin-bottom: .5em;
    line-height: 25px;
    font-size: 12px;
    color: #ff4757;
}

/* 歌名 */
.name{
    font-size: 28px;
    font-weight: 700;
    margin-bottom: .8em;
    line-height: 1.2;
}
.nickname{
    margin-bottom: 2em;
}
.subscribers-txt{
    margin-bottom: .6em;
}
/* 播放量 父组件*/
.playnumber{
    margin-bottom: .5em;
    font-size: 16px;
    color: #333;
}
.playcount-txt{
    float: left;
}
/* 文字描述 */
.description{
    color: #666;
    font-size: 13px;
    /* 文字识别换行符 */
    /* white-space: pre-line; */
}

/* 相关歌单推荐 */
.recommend-txt{
    font-size: 24px;
    font-weight: 500;
    margin: 20px 0 10px 0;
}
.recommend-songlist{
    float: left;
    width: calc(20% - 20px);
    margin: 10px 10px;

    /* 告诉浏览器，padding包含在宽度中 */
    box-sizing: border-box;

}
/* 鼠标悬浮时，图片拉近效果 */
.recommend-songlistimg:hover {
    /* 悬浮时拉近图片 */
    transform: scale(1.1);
    /* 延时 */
    transition: all 1s ease 0s;
    cursor: pointer;
}
.recommend-image{
    position: relative;
    /* 宽高等比例 */
    height: 0;
    padding-top: 100%;
    /* 图片拉近时，高度会变大，因此需要隐藏高度上溢出的部分 */
    overflow: hidden;
}
.recommend-songlistimg{
    border-radius: 3px;
    /* 延时 */
     transition: all 1s ease 0s;
    /* 父元素有了padding值，子元素则需修改定位 以显示在正确位置 -2*/
     position: absolute;
     top: 0;
}
.songlist-name{
    margin: 10px 5%;
    font-size: 14px;
    font-weight: 700;
    /* 显示2行。超出部分显示".." */
    overflow: hidden;
    display: -webkit-box;
     -webkit-box-orient:vertical;
    -webkit-line-clamp: 2;
    height:37px;
}
.recommend-creator{
    margin: 10px 5%;
    color: #999;
    /* 显示1行。超出部分显示".." */
    overflow: hidden;
    display: -webkit-box;
     -webkit-box-orient:vertical;
    -webkit-line-clamp: 1;
}
.creator-name{
    color: #000;
    font-size: 14px;
    font-weight: 500;
}
.comments{
    width: 90%;
    margin: 0px auto;
}
.hot-comments{
    margin-top: 40px;
    margin-bottom: 40px;
}
.comments-txt{
    font-weight: 700;
    font-size: 24px;
}
.comments-title{
    font-size: 14px;
    font-weight: 700;
}
.comments-body{
    margin-top: 20px;
}
/* 评论者头像 */
.comments-avatarimg{
    width: 35px;
    border-radius: 50%;
    cursor: pointer;
    float: left;
}
.comments-nickname{
    float: left;
    margin-left: 10px;
    font-size: 14px;
    color: rgba(51,51,51,.6);
    line-height: 35px;
}
.comments-time{
    float: left;
    line-height: 35px;
    margin-left: 20px;
    font-size: 14px;
    color: rgba(51,51,51,.3);
}
.comment-content{
    /* 底部留有部分距离，可以在不设置高度的情况下样式美观，设置高度会导致无法根据文字自适应显示 */
    padding-bottom: 15px;
    padding-left: 45px;
    /* height: 62px; */
    line-height: 22px;
    color: #333;
    font-size: 14px;
    font-weight: 400;
    /* 显示3行。超出部分显示".." */
    /* overflow: hidden;
    display: -webkit-box;
     -webkit-box-orient:vertical;
    -webkit-line-clamp: 3; */
}
/* 评论分割线 */
.line{
    border-bottom: 1px #dedeee double;
    margin-left: 45px;
}
.pagination{
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
.main{
    /* border: 1px solid green; */
    /* height: 100px; */
    padding: 0 5%;
}
.footer{
    /* border: 1px solid red; */
    height: 100px !important;
}

/* 清除浮动 */
.clearfix{
    clear: both;
}

</style>
